package main

import (
	"encoding/csv"
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"
)

func main() {

	// 读取文件
	//dir := "/data/twm/realtime/cimiss/SURF_CHN_MUL_HOR/TEM_2019"
	//dir := "D:\\data\\CIMISS\\SURF_CHN_MUL_HOR\\PRS"
	//dir_new := "D:\\data\\CIMISS\\SURF_CHN_MUL_HOR\\PRS_"
	dir := os.Args[2]
	dir_new := os.Args[3]

	_ = filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			fmt.Printf("通过处理访问路径失败来防止奔溃 %q: %v\n", path, err)
			return err
		}

		if !info.IsDir() {
			csvStr := make([][]string, 0)
			readFile, err := ioutil.ReadFile(path)
			if err != nil {
				fmt.Println("读取报错:", path, "--------", err)
			}
			newReader := csv.NewReader(strings.NewReader(string(readFile)))
			readAll, err := newReader.ReadAll()
			if err != nil {
				fmt.Println("读取到的解析不成csv文本:", err)
			}
			for _, value := range readAll {
				if value[0] == os.Args[1] { // 680069         769625
					//fmt.Println("filePath:", path, ";value:", value)
					csvStr = append(csvStr, value)
				}
			}
			if len(csvStr) > 0 {
				fileName := filepath.Base(path)
				fileNameNew := filepath.Join(dir_new+fileName[:4], fileName[:4], fileName[4:6], fileName)
				fmt.Println("filePath:", fileNameNew)
				err := os.MkdirAll(filepath.Dir(fileNameNew), os.ModePerm)
				if err != nil {
					fmt.Println("创建文件夹错误：", err)
				}
				open, err := os.OpenFile(fileNameNew, os.O_CREATE|os.O_APPEND|os.O_RDWR, os.ModePerm)
				if err != nil {
					fmt.Println("打开||创建文件错误：", err)
				}
				newWriter := csv.NewWriter(open)
				err = newWriter.WriteAll(csvStr)
				if err != nil {
					fmt.Println("写入文件错误：", err)
				}
				newWriter.Flush()
				open.Close()
			}
		}

		return nil
	})

}
